#!/usr/bin/env python3
"""
KidsBuddy 依赖包安装脚本

自动安装项目所需的依赖包，支持不同的安装模式。
"""

import sys
import subprocess
import argparse
from pathlib import Path


def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"🐍 当前 Python 版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major == 3 and version.minor >= 10:
        print("✅ Python 版本符合要求 (3.10+)")
        return True
    else:
        print("❌ Python 版本不符合要求，需要 3.10+")
        print("请升级到 Python 3.10 或更高版本")
        return False


def run_command(command, description):
    """运行命令并显示结果"""
    print(f"🔧 {description}...")
    print(f"   命令: {command}")
    
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            check=True, 
            capture_output=True, 
            text=True
        )
        print(f"✅ {description} 成功")
        if result.stdout:
            print(f"   输出: {result.stdout.strip()}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败")
        print(f"   错误: {e.stderr.strip()}")
        return False


def install_basic_dependencies():
    """安装基础依赖"""
    print("\n📦 安装基础依赖包...")
    return run_command(
        "pip install -r requirements.txt",
        "安装基础依赖"
    )


def install_development_dependencies():
    """安装开发依赖"""
    print("\n🛠️ 安装开发依赖包...")
    return run_command(
        'pip install -e ".[dev]"',
        "安装开发依赖"
    )


def install_optional_dependencies(options):
    """安装可选依赖"""
    if not options:
        return True
    
    print(f"\n🔌 安装可选依赖包: {', '.join(options)}...")
    
    for option in options:
        success = run_command(
            f'pip install -e ".[{option}]"',
            f"安装 {option} 依赖"
        )
        if not success:
            return False
    
    return True


def install_all_dependencies():
    """安装所有依赖"""
    print("\n🎯 安装所有依赖包...")
    return run_command(
        'pip install -e ".[all]"',
        "安装所有依赖"
    )


def upgrade_pip():
    """升级pip"""
    print("⬆️ 升级 pip...")
    return run_command(
        "pip install --upgrade pip",
        "升级 pip"
    )


def validate_installation():
    """验证安装"""
    print("\n🔍 验证安装...")
    script_path = Path(__file__).parent / "validate_requirements.py"
    
    if script_path.exists():
        return run_command(
            f"python {script_path}",
            "验证依赖包安装"
        )
    else:
        print("⚠️ 验证脚本不存在，跳过验证")
        return True


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="KidsBuddy 依赖包安装脚本",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
安装模式:
  basic     - 仅安装基础运行时依赖
  dev       - 安装开发环境依赖
  all       - 安装所有依赖 (包括可选功能)
  custom    - 自定义安装特定可选依赖

可选依赖:
  audio     - 音频处理功能
  hardware  - 硬件接口功能
  database  - 数据库支持功能
  ocr       - OCR文字识别功能

示例:
  python scripts/install_dependencies.py --mode basic
  python scripts/install_dependencies.py --mode dev
  python scripts/install_dependencies.py --mode custom --optional audio hardware
  python scripts/install_dependencies.py --mode all
        """
    )
    
    parser.add_argument(
        "--mode",
        choices=["basic", "dev", "all", "custom"],
        default="basic",
        help="安装模式 (默认: basic)"
    )
    
    parser.add_argument(
        "--optional",
        nargs="*",
        choices=["audio", "hardware", "database", "ocr"],
        help="要安装的可选依赖 (仅在 custom 模式下使用)"
    )
    
    parser.add_argument(
        "--no-upgrade-pip",
        action="store_true",
        help="不升级 pip"
    )
    
    parser.add_argument(
        "--no-validate",
        action="store_true",
        help="不验证安装结果"
    )
    
    args = parser.parse_args()
    
    print("🚀 KidsBuddy 依赖包安装脚本")
    print("=" * 50)
    
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 升级pip
    if not args.no_upgrade_pip:
        if not upgrade_pip():
            print("⚠️ pip 升级失败，继续安装...")
    
    # 根据模式安装依赖
    success = True
    
    if args.mode == "basic":
        success = install_basic_dependencies()
    
    elif args.mode == "dev":
        success = install_basic_dependencies() and install_development_dependencies()
    
    elif args.mode == "all":
        success = install_all_dependencies()
    
    elif args.mode == "custom":
        success = install_basic_dependencies()
        if success and args.optional:
            success = install_optional_dependencies(args.optional)
    
    if not success:
        print("\n❌ 安装过程中出现错误")
        sys.exit(1)
    
    # 验证安装
    if not args.no_validate:
        if not validate_installation():
            print("\n⚠️ 验证过程中出现问题，但安装可能已成功")
    
    print("\n🎉 依赖包安装完成!")
    print("\n💡 下一步:")
    print("   1. 运行测试: python -m pytest tests/")
    print("   2. 启动应用: python -m kidsbuddy")
    print("   3. 查看文档: docs/README.md")


if __name__ == "__main__":
    main()
